#!/usr/bin/python
# -*- coding: utf-8 -*-

"""
   Галерея, основанная на picasaweb
"""

import logging
import config
import gdata.docs.service
import gdata.docs
from gdata.alt import appengine
from google.appengine.ext import webapp
from engine import settings
from engine import pagegen

# enable info logging by the app
logging.getLogger().setLevel(logging.INFO)

def getDoc(id = 'none', dtype = 'all'):
  """
  Args:
    id: 
    dtype: 

  Returns:
  """
  try:
    gd_client = gdata.docs.service.DocsService()
    gd_client.email = config.GD_mail
    gd_client.password = config.GD_password
    gd_client.source = 'fooCMS-portal-2'
    gd_client.debug = settings.DEBUG
    gdata.alt.appengine.run_on_appengine(gd_client)
    gd_client.ProgrammaticLogin()

    if dtype == 'all':
      data = gd_client.GetDocumentListFeed()
    elif (dtype != 'all') and (id == 'none'):
      query = gdata.docs.service.DocumentQuery(categories = [dtype])
      data = gd_client.Query(query.ToUri())
    elif id != 'none':
      data = 'doc loaded here'
  except Exception, error:
    data = { 'error': 'Sorry, dude, service can`t load docs, please, come back later...' }
    logging.error('getDoc: Error = %s; id = %s' % (error, id) )

  return data

class DocsHandler(webapp.RequestHandler):
  """
  """
  def get(self):
    """
    Args:
      self: 
    """

    doc_id = self.request.get('id', default_value = 'none')
    doc_type = self.request.get('type', default_value = 'all')

    page_template_values = {
      'portal_title': 'Документы ' + settings.SITETITLE,
      'page_description': 'документы для изучения',
    }

    data = getDoc(doc_id, doc_type)
    if type(data) == dict:
      action = 'error'
      entrys = data
    else:
      action = doc_type
      entrys = []
      for e in data.entry:
        id = e.id.text.split('/')
        id = id[len(id) - 1].split('%3A')
        dtype = id[0]
        id = id[1]
        entrys += [{ 'id': id,
                     'title': e.title.text, #.encode('UTF-8'),
                     'type': dtype,
                     #'link': 'http://%s.google.com/%s?%s=' % (id)# e.GetAlternateLink().href
                      }]

    page_template_values.update(action = action, entrys = entrys)
    pagegen.generatePage(self, 'docs', page_template_values)